﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 项目服务
    /// </summary>
    [Route("api/ProjectManage")]
    [ApiDescriptionSettings("仓库基础数据", Name = "ProjectManage", Order = 100)]

    public class ProjectManageService : IDynamicApiController, ITransient
    {
        private readonly IRepository<ProjectManage, MasterDbContextLocator> _projectManageRep; //项目管理仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="projectManageRep"></param>
        public ProjectManageService(
            IRepository<ProjectManage, MasterDbContextLocator> projectManageRep
        )
        {
            _projectManageRep = projectManageRep;
        }
        #endregion

        /// <summary>
        /// 分页查询项目管理
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<ProjectManageOutput>> Page([FromQuery] ProjectManageSearch input)
        {
            return await _projectManageRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(input.Code), u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.Name), u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.SearchBeginTime), u => u.CreatedTime >= DateTime.Parse(input.SearchBeginTime.Trim()) &&
                 u.CreatedTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                .OrderBy(PageInputOrder.OrderBuilder<ProjectManageSearch>(input))
                .ProjectToType<ProjectManageOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);
        }

        /// <summary>
        /// 新增项目管理
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddProjectManageInput input)
        {
            var isExist = await _projectManageRep.DetachedEntities.AnyAsync(u => u.Code.Equals(input.Code));
            if (isExist) throw Oops.Oh("数据已存在");

            var projectManage = input.Adapt<ProjectManage>();
            await _projectManageRep.InsertAsync(projectManage);
        }
    }
}
